package cheme.ProcessModel.Table;

import java.io.IOException;
import java.io.StringReader;

import cheme.ProcessModel.IModelElement;
import cheme.ProcessModel.IPropertyAware;
import cheme.ProcessModel.IXmlOperations;
import cheme.ProcessModel.ProcessModelConstants;
import cheme.ProcessModel.XmlHelper;

import javax.xml.parsers.*;

import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
/*
 * This 
 */

public class WritableField extends Field implements IWritableField, ITextModel, IXmlOperations
{
	/*
	 * Serialization version identifier. (Set to default for now)
	 */
	
	private static final long serialVersionUID = 1L;
	
	/*
	 * The 'type' of a field is the type of event that will be fired (i8n
	 * addition to a standard P_TEXT event) when the setText method is invoked.
	 * By default no type is assigned and not event will be fired.
	 */
	
	private String type = null;
	
	public WritableField(IModelElement parent, String text)
	{
		super(parent, text);
	}
	
	public WritableField(IModelElement parent, String text, String type)
	{
		super(parent, text);
		this.type = type;
	}

	public String getType()
	{
		return type;
	}
	
	public void setText(String text)
	{
		if(null != text && !getText().equals(text.trim()))
		{
			String old = getText();
			
			this.text = text.trim();

			firePropertyChange(IPropertyAware.P_TEXT, old, this.text);
			
			if(getType() != null && getType() != IPropertyAware.P_TEXT)
			{
				firePropertyChange(getType(), old, this.text);
			}
		}
	}
	
	public void set(Field value)
	{
		if(value instanceof WritableField)
		{
			setText(((SelectionField)value).getText());
		}
	}
	
	public Object fromXml() {
		// TODO Auto-generated method stub
		return null;
	}

	public String toXml() {
		
		//Writable fields have a modified "type" attribute from the
		//base "Field" class.  We need to make sure that the change
		//is reflected in our XML
		String xml = super.toXml();
		Document doc = (Document)XmlHelper.xmlFromString(xml);
		Element e1 = doc.getDocumentElement();
		e1.setAttribute("type", this.type);
		
		xml = XmlHelper.xmlToString(doc);
		return xml;
	}
}
